﻿package ygg.encoding.amf.type.v3
{
	import ygg.encoding.amf.type.*;
	import ygg.encoding.amf.*;
	import j.sus2maj7.encoding.*;
	
	public class StringCodec extends Amf3Codec
	{
		public function StringCodec()
		{
			
		}
		
		override public function decode(binary:IBinary, context:IContext=null):*
		{
			var u:uint = AmfBinary(binary).decodeU29();
			
			if ( u & 1 ) //U29S-value
			{
				var s:String = binary.readUTFBytes(u >>> 1);
				AmfContext(context).addString(s);
				return s;
			}
			else //U29S-ref
			{
				return AmfContext(context).getString(u >>> 1);
			}
		}
		
		override public function encode(o:*, context:IContext=null):IBinary
		{
			var i:int = AmfContext(context).indexOfString(o);
			
			trace('indexOfString', i);
			var s:String = o as String;
			
			var b:AmfBinary = new AmfBinary();
			b.writeByte(Amf3Marker.STRING);
			trace('encoding string', s);
			
			if ( i > -1 ) //u29x-ref x0
			{
				trace('u29S-ref');
				i <<= 1;
				//i |= 0;
				
				b.encodeU29(i);
			}
			else //U29x-value
			{
				trace('U29S-value');
				if (s.length > 0)
					AmfContext(context).addString(s);
					
				b.encodeU29(s.length << 1 | 1);
				
				b.writeUTFBytes(s);
			}
			
			return b;
		}
	}
	
}